import { Extension } from '@codemirror/state';
import { lineNumbers } from '@codemirror/view';
import ancher from 'markdown-it-anchor';
import { Themes, config } from 'md-editor-v3';
import { ToolbarNames } from 'md-editor-v3/lib/types';
export interface MDEditorOpts {
    lineNumber?: boolean;
    ancher?: boolean;
    renderDelay?: number;
}

const codeMirrorExtensions = (_theme: Themes, extensions: Extension[], opts: MDEditorOpts) => {
    const p = [...extensions];
    opts.lineNumber && p.push(lineNumbers());
    return p
}

const markdownItConfig = (mdit: any, opts: MDEditorOpts) => {
    opts.ancher && mdit.use(ancher);
}
const toolbars = [
    'bold', 'underline', 'italic',
    '-',
    'title', 'strikeThrough', 'sub', 'sup', 'quote', 'unorderedList', 'orderedList', 'task',
    '-',
    'codeRow', 'code', 'link', 'image', 'table', 'mermaid', 'katex',
    '-',
    'revoke', 'next', 'save',
    '=',
    0, 'pageFullscreen', 'fullscreen', 'preview', 'htmlPreview', 'catalog', 'github'
] as ToolbarNames[];
export const useMDEditor = (opts: MDEditorOpts) => {

    config({
        codeMirrorExtensions: (_theme, extensions) => codeMirrorExtensions(_theme, extensions, opts),
        markdownItConfig: (mdit) => markdownItConfig(mdit, opts),
        editorConfig: { renderDelay: opts.renderDelay }// 输入渲染延迟（ms）
    });

    async function onSave(v: string, h: Promise<string>) {
        const title = v.split('\n')[0].replace('#', '').trim();
        const content = await h;
        console.log(title, content);

    }

    function onDraft() {

    }


    return {
        toolbars
    }
}